<template>
  <div class="list-container">
      <div class='search-area'>
          <div class='search-left'>
              <div class='input-line'>
                  <span class='label'>商户名：</span>
                  <el-input placeholder="请输入商户名" label='商户名' v-model="searchParams.merchantName"/>
              </div>
              <div class='input-line'>
                  <span class='label'>订单号：</span>
                  <el-input placeholder="请输入订单号" label='商户名' v-model="searchParams.orderNo"/>
              </div>
              <div class='input-line'>
                  <span class='label'>日期：</span>
                  <el-date-picker
                      v-model="searchParams.placedFrom"
                      type="date"
                      value-format='yyyy-MM-dd'
                      placeholder="选择日期">
                  </el-date-picker>
                  <div class='gap'>-</div>
                  <el-date-picker
                      v-model="searchParams.placedTo"
                      type="date"
                      value-format='yyyy-MM-dd'
                      placeholder="选择日期">
                  </el-date-picker>
              </div>
          </div>
          <div class='search-right'>
              <el-button type="primary" @click='_getOrderList'>查询</el-button>
              <el-button type="primary" @click='_ordersExport'>导出</el-button>
          </div>
      </div>
      <el-table
          fit
          :data="tableData"
          style="width: 100%">
          <el-table-column
              prop="orderNo"
              label="订单ID">
          </el-table-column>
          <el-table-column
              prop="insuranceNo"
              label="保单号">
          </el-table-column>
          <el-table-column
              prop="orderPlacedDate"
              label="申请日期">
          </el-table-column>
          <el-table-column
              prop="effectiveDate"
              label="生效日期">
          </el-table-column>
          <el-table-column
              prop="buyerName"
              label="权益人姓名">
          </el-table-column>
          <el-table-column
              prop="buyerIdNo"
              label="身份证号">
          </el-table-column>
          <el-table-column
              prop="buyerMobileNo"
              label="手机号">
          </el-table-column>
          <el-table-column
              label="驾驶城市">
              <template slot-scope="scope">
                  <span>{{scope.row.region.name}}</span>
              </template>
          </el-table-column>
          <el-table-column
              prop="vehicleName"
              label="驾驶车型">
          </el-table-column>
          <el-table-column
              prop="vin"
              label="车架号">
          </el-table-column>
          <el-table-column
              prop="engineNo"
              label="发动机号">
          </el-table-column>
          <el-table-column
              prop="merchantName"
              label="商户名">
          </el-table-column>
          <el-table-column
              label="权益状态">
              <template slot-scope="scope">
                  <span v-if='scope.row.serviceStatus === 1'>未使用</span>
                  <span v-if='scope.row.serviceStatus === 2'>处理中</span>
                  <span v-if='scope.row.serviceStatus === 3'>处理完成</span>
              </template>
          </el-table-column>
          <el-table-column
              align='center'
              label="操作"
              width='200'>
              <template slot-scope="scope">
                  <div style='display: flex;align-items: center;justify-content: center'>
                      <el-button style='flex-shrink: 0' v-if='scope.row.serviceStatus === 2' type='primary' size='mini' @click='_statusChange(scope.row.orderNo)'>处理完成</el-button>
                      <el-button style='flex-shrink: 0' type='primary' size='mini' @click='bindInsuranceNo(scope.row.orderPlacedDate)'>录入保单</el-button>
                  </div>
              </template>
          </el-table-column>
      </el-table>
      <div class='pagination'>
          <el-pagination
              background
              layout="prev, pager, next"
              :current-page='currentPage'
              :page-size='10'
              :total="total"
              @current-change='onPageChange'
          >
          </el-pagination>
      </div>
  </div>
</template>

<script>
import { getOrderList, ordersExport, insuranceNoBind, statusChange } from '@/api/order'
export default {
    data() {
        return {
            searchParams: {
                merchantName: '', // 商户名称
                orderNo: '', // 订单ID
                pageNum: 1, // 分页号
                pageSize: 10, // 单页数据条数
                placedFrom: '', // 起始申请日期(yyyy-MM-dd)
                placedTo: '' // 截止申请日期(yyyy-MM-dd)
            },
            currentPage: 1,
            total: 0,
            tableData: []
        }
    },
    mounted() {
        // this._getOrderList()
    },
    methods: {
        onPageChange(page) {
            this.currentPage = page
        },
        // 获取订单列表
        async _getOrderList(currentPage) {
            let { searchParams } = this
            let res = await getOrderList(searchParams)
            this.tableData = res.records
            this.total = +res.total
            this.currentPage = +res.page
            console.log(res, '订单列表')
        },

        onSearchClick() {
            this._getOrderList(1)
        },

        // 订单导出
        async _ordersExport() {
            let { searchParams } = this
            let _date = this.dateFormat('YYYY-mm-dd HH:MM', new Date())
            let res = await ordersExport(searchParams)
            const BLOB = new Blob([res]) // Blob 对象表示一个不可变、原始数据的类文件对象（File 接口都是基于Blob）
            const fileReader = new FileReader() // FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件的内容
            fileReader.readAsDataURL(BLOB) // 开始读取指定的Blob中的内容。一旦完成，result属性中将包含一个data: URL格式的Base64字符串以表示所读取文件的内容
            fileReader.onload = (event) => { // 处理load事件。该事件在读取操作完成时触发
                // 新建个下载的a标签，完成后移除。
                let a = document.createElement('a')
                a.download = `订单列表-${_date}.xlsx`
                a.href = event.target.result
                document.body.appendChild(a)
                a.click()
                document.body.removeChild(a)
            }
        },

        // 时间格式化
        dateFormat(fmt, date) {
            let ret
            const opt = {
                'Y+': date.getFullYear().toString(), // 年
                'm+': (date.getMonth() + 1).toString(), // 月
                'd+': date.getDate().toString(), // 日
                'H+': date.getHours().toString(), // 时
                'M+': date.getMinutes().toString(), // 分
                'S+': date.getSeconds().toString() // 秒
                // 有其他格式化字符需求可以继续添加，必须转化成字符串
            }
            for (let k in opt) {
                ret = new RegExp('(' + k + ')').exec(fmt)
                if (ret) {
                    fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
                }
            }
            return fmt
        },
        // 关联保单
        bindInsuranceNo(orderPlacedDate) {
            this.$prompt('请输入保单号', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(({ value }) => {
                this._insuranceNoBind(value, orderPlacedDate)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消输入'
                })
            })
        },
        // 关联保单请求
        async _insuranceNoBind(insuranceNo, orderPlacedDate) {
            let params = { insuranceNo, orderPlacedDate }
            let res = await insuranceNoBind(params)
            if (res.code === '200') {
                this.$message({
                    type: 'success',
                    message: '录入成功'
                })
                this._getOrderList()
            } else {
                this.$message({
                    type: 'error',
                    message: res.message
                })
            }
        },

        // 订单状态变更
        async _statusChange(orderNo) {
            let params = {
                orderNo,
                serviceStatus: 3
            }
            let res = await statusChange(params)
            if (res.code === '200') {
                this.$message({
                    type: 'success',
                    message: '状态变更成功'
                })
                this._getOrderList()
            } else {
                this.$message({
                    type: 'error',
                    message: res.message
                })
            }
        }
    }
}
</script>
<style lang='scss'>
    .list-container{
        .search-area{
            display: flex;
            align-items: center;
            width: 100%;
            padding: 20px 0;
            border-bottom: 1px solid #f2f2f2;
            .search-left{
                display: flex;
                align-items: center;
                justify-content: center;
                .input-line{
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin-right: 20px;
                    .label{
                        flex-shrink: 0;
                    }
                    .gap{
                        padding: 0 10px;
                    }
                }
            }
            .search-right{
                display: flex;
                justify-content: flex-end;
                margin-left: 20px;
            }
        }
        .pagination{
            margin-top: 20px;
        }
    }
</style>
